package utils

import (
	"errors"
	"github.com/gin-gonic/gin"
	"sort"
)

type Routes struct {
	Routes  []*Route
	BaseUrl string
}

func (r *Routes) Register(engine *gin.Engine) {
	for i := range r.Routes {
		tempRoute := r.Routes[i]
		tempRoute.Path = r.BaseUrl + tempRoute.Path
		err := tempRoute.register(engine)
		if err != nil {
			panic(err)
		}
	}
}

type Route struct {
	Path         string
	Method       string
	View         func(c *gin.Context)
	Body         any
	ResponseJson any
}

func (r *Route) register(engine *gin.Engine) (err error) {
	if sort.SearchStrings([]string{"POST", "GET", "PUT", "DELETE"}, r.Method) < 0 {
		err = errors.New("only support \"POST\", \"GET\", \"PUT\", \"DELETE\"")
	} else {
		//log.Println("register: " + r.Method + " -- " + r.Path)
		engine.Handle(
			r.Method,
			r.Path,
			r.View,
		)
	}
	return err
}
